<div class="p-4">
    @if (isLoading()) {
        <mat-spinner [diameter]="32"></mat-spinner>
    } @else if (errorLoading()) {
        <div class="text-red-500 p-4 border border-red-300 rounded bg-red-50">
            {{ errorLoading() }}
        </div>
    } @else {
        @if (iterations().length > 0) {
            <mat-accordion multi>
                @for (iteration of iterations(); track trackByIteration($index, iteration)) {
                    <mat-expansion-panel class="mb-2" #expansionPanel (opened)="fetchIterationDetails(iteration)">
                        <mat-expansion-panel-header>
                            <mat-panel-title>
                                Iteration #{{ iteration.iteration }}
                            </mat-panel-title>
                            <span>
                                @if (iteration.error) {
                                    <mat-panel-description class="text-red-600 font-semibold flex items-center">
                                        <mat-icon color="warn" class="mr-1 icon-size-5">error_outline</mat-icon>
                                        Ended with error
                                    </mat-panel-description>
                                }
                            </span>
                        </mat-expansion-panel-header>
                        <ng-template matExpansionPanelContent>
                            @let detailState = expandedIterationData()[iteration.iteration];
                            @if (expansionPanel.expanded) {
                                <div class="py-2">
                                    @if (detailState?.status === 'loading') {
                                        <div class="flex justify-center items-center p-4">
                                            <mat-spinner [diameter]="32"></mat-spinner> <span class="ml-2">Loading details...</span>
                                        </div>
                                    } @else if (detailState?.status === 'success' && detailState?.data) {
                                        {{ iteration.summary }}
                                        <br/>
                                        <!-- Functions -->
                                        <div class="mb-3">
                                            <h4 class="font-medium text-lg mb-1">Functions Available:</h4>
                                            <mat-chip-listbox aria-label="Functions used">
                                                @for (func of detailState.data.functions; track func) {
                                                    <mat-chip>{{ func }}</mat-chip>
                                                }
                                            </mat-chip-listbox>
                                        </div>

                                        <!-- Input Prompt -->
                                        <div class="mb-3">
                                            <h4 class="font-medium text-lg mb-1">Input Prompt:</h4>
                                            <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto">
                                                <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.prompt || 'N/A' }}</pre>
                                            </div>
                                        </div>

                                        <!-- Agent Reasoning/Plan Tabs -->
                                        @if (detailState.data.expandedUserRequest || detailState.data.observationsReasoning || detailState.data.agentPlan || detailState.data.nextStepDetails) {
                                            <div class="mb-3">
                                                <h4 class="font-medium text-lg mb-1">Agent Reasoning & Plan:</h4>
                                                <mat-tab-group animationDuration="0ms">
                                                    @if (detailState.data.expandedUserRequest) {
                                                        <mat-tab label="Expanded Request">
                                                            <ng-template matTabContent>
                                                                <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                                    <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.expandedUserRequest }}</pre>
                                                                </div>
                                                            </ng-template>
                                                        </mat-tab>
                                                    }
                                                    @if (detailState.data.observationsReasoning) {
                                                        <mat-tab label="Observations/Reasoning">
                                                            <ng-template matTabContent>
                                                                <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                                    <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.observationsReasoning }}</pre>
                                                                </div>
                                                            </ng-template>
                                                        </mat-tab>
                                                    }
                                                    @if (detailState.data.agentPlan) {
                                                        <mat-tab label="Plan">
                                                            <ng-template matTabContent>
                                                                <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                                    <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.agentPlan }}</pre>
                                                                </div>
                                                            </ng-template>
                                                        </mat-tab>
                                                    }
                                                    @if (detailState.data.nextStepDetails) {
                                                        <mat-tab label="Next Step Details">
                                                            <ng-template matTabContent>
                                                                <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                                    <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.nextStepDetails }}</pre>
                                                                </div>
                                                            </ng-template>
                                                        </mat-tab>
                                                    }
                                                </mat-tab-group>
                                            </div>
                                        }

                                        <!-- Generated Code Tabs -->
                                        <div class="mb-3">
                                            <h4 class="font-medium text-lg mb-1">Code Generation:</h4>
                                            <mat-tab-group animationDuration="0ms">
                                                <mat-tab label="Draft Generated Code">
                                                    <ng-template matTabContent>
                                                        <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                            <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.draftCode }}</pre>
                                                        </div>
                                                    </ng-template>
                                                </mat-tab>
                                                <mat-tab label="Code Review">
                                                    <ng-template matTabContent>
                                                        <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                            <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.codeReview }}</pre>
                                                        </div>
                                                    </ng-template>
                                                </mat-tab>
                                                <mat-tab label="Generated Code">
                                                    <ng-template matTabContent>
                                                        <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                            <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.code }}</pre>
                                                        </div>
                                                    </ng-template>
                                                </mat-tab>
                                                <mat-tab label="Executed Code">
                                                    <ng-template matTabContent>
                                                        <div class="bg-gray-100 p-2 rounded border border-gray-200 max-h-60 overflow-y-auto mt-2">
                                                            <pre class="whitespace-pre-wrap text-sm">{{ detailState.data.executedCode }}</pre>
                                                        </div>
                                                    </ng-template>
                                                </mat-tab>
                                            </mat-tab-group>
                                        </div>

                                        <!-- Function Calls -->
                                        @if (detailState.data.functionCalls && detailState.data.functionCalls.length > 0) {
                                            <div class="mb-3">
                                                <h4 class="font-medium text-lg mb-1">Function Calls Executed:</h4>
                                                <div class="space-y-2">
                                                    @for (call of detailState.data.functionCalls; track call.function_name + $index) {
                                                        <mat-card class="!shadow-sm border" [ngClass]="{'border-red-300 bg-red-50': hasError(call)}">
                                                            <mat-card-header class="!pt-2 !pb-1">
                                                                <mat-card-title class="!text-base !font-semibold flex items-center">
                                                                    @if (hasError(call)) {
                                                                        <mat-icon color="warn" class="mr-1 icon-size-5">error</mat-icon>
                                                                    }
                                                                    {{ call.function_name }}
                                                                </mat-card-title>
                                                            </mat-card-header>
                                                            <mat-card-content class="!pb-2">
                                                                <div class="text-sm mb-1"><strong>Parameters:</strong></div>
                                                                <pre class="bg-gray-100 p-2 rounded text-xs max-h-40 overflow-y-auto">{{ call.parameters | json }}</pre>

                                                                @if (call.stdout) {
                                                                    <div class="mt-2">
                                                                        <div class="text-sm mb-1"><strong>Output (stdout):</strong></div>
                                                                        <pre class="bg-green-50 border border-green-200 p-2 rounded text-xs max-h-40 overflow-y-auto">{{ call.stdout }}</pre>
                                                                    </div>
                                                                }
                                                                @if (call.stderr) {
                                                                    <div class="mt-2">
                                                                        <div class="text-sm mb-1 text-red-700"><strong>Error (stderr):</strong></div>
                                                                        <pre class="bg-red-50 border border-red-200 p-2 rounded text-xs max-h-40 overflow-y-auto">{{ call.stderr }}</pre>
                                                                    </div>
                                                                }
                                                            </mat-card-content>
                                                        </mat-card>
                                                    }
                                                </div>
                                            </div>
                                        }

                                        <!-- Memory -->
                                        @if (detailState.data.memory && (detailState.data.memory | keyvalue).length > 0) {
                                            <div class="mb-3">
                                                <h4 class="font-medium text-lg mb-1">Memory State:</h4>
                                                <mat-accordion multi>
                                                    @for (item of detailState.data.memory | keyvalue; track item.key) {
                                                        <mat-expansion-panel class="mb-1 !shadow-sm border">
                                                            <mat-expansion-panel-header>
                                                                <mat-panel-title class="!text-sm !font-semibold">
                                                                    {{ item.key }}
                                                                </mat-panel-title>
                                                            </mat-expansion-panel-header>
                                                            <div class="bg-gray-50 p-2 rounded text-xs max-h-40 overflow-y-auto">
                                                                <pre class="whitespace-pre-wrap">{{ item.value }}</pre>
                                                            </div>
                                                        </mat-expansion-panel>
                                                    }
                                                </mat-accordion>
                                            </div>
                                        }

                                        <!-- Live Files  -->
                                        @if (detailState.data.toolState && detailState.data.toolState['LiveFiles'] && detailState.data.toolState['LiveFiles'].length > 0) {
                                            <div class="mb-3">
                                                <h4 class="font-medium text-lg mb-1">Live Files:</h4>
                                                <mat-chip-listbox aria-label="Live files">
                                                    @for (file of detailState.data.toolState['LiveFiles']; track file) {
                                                        <mat-chip>{{ file }}</mat-chip>
                                                    }
                                                </mat-chip-listbox>
                                            </div>
                                        }

                                        <!-- File Store  -->
                                        @if (detailState.data.toolState && detailState.data.toolState['FileStore'] && detailState.data.toolState['FileStore'].length > 0) {
                                            <div class="mb-3">
                                                <h4 class="font-medium text-lg mb-1">File Store:</h4>
                                                <div class="space-y-2">
                                                    @for (file of detailState.data.toolState['FileStore']; track file.filename) {
                                                        <mat-card class="!shadow-sm border">
                                                            <mat-card-content class="!pb-2 !pt-2">
                                                                <div class="text-sm"><strong>{{ file.filename }}</strong></div>
                                                                <div class="text-xs text-gray-600">{{ file.description }}</div>
                                                                <div class="text-xs text-gray-500">Size: {{ file.size }} bytes, Last Updated: {{ file.lastUpdated | date:'short' }}</div>
                                                            </mat-card-content>
                                                        </mat-card>
                                                    }
                                                </div>
                                            </div>
                                        }

                                        <!-- Iteration Error from full AutonomousIteration data -->
                                        @if (detailState.data.error) {
                                            <div class="mt-3 p-3 border border-red-300 rounded bg-red-50">
                                                <h4 class="font-medium text-lg mb-1 text-red-700">Iteration Error:</h4>
                                                <pre class="whitespace-pre-wrap text-sm text-red-800">{{ detailState.data.error }}</pre>
                                            </div>
                                        }
                                    } @else if (detailState?.status === 'error') {
                                        <div class="text-red-500 p-4 border border-red-300 rounded bg-red-50">
                                            Error loading details: {{ detailState.error?.message || 'Unknown error' }}
                                        </div>
                                    } @else {
                                        <!-- Panel is open, but fetch hasn't completed or started for some reason, or no data yet -->
                                        <!-- This state should ideally be brief if (opened) triggers fetch correctly -->
                                        <div class="flex justify-center items-center p-4 text-gray-500">
                                            Select an iteration to view details.
                                        </div>
                                    }
                                </div>
                            }
                        </ng-template>
                    </mat-expansion-panel>
                }
            </mat-accordion>
        } @else {
            <div class="text-gray-500 p-4 text-center">
                No iteration data available for this agent.
            </div>
        }
    }
</div>
